package com.heima.juc.unlock;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 19:11
 */
@Slf4j(topic = "c.Test2")
public class Test2 {

    static AtomicReference<String> reference = new AtomicReference<>("A");

    public static void main(String[] args) {
        log.debug("main start....");
        //获取值 A
        //这个共享变量被其他线程修改过
        String prev = reference.get();
        other();
        Sleeper.sleep(1);
        // 尝试改为 C
        log.debug("change A -> C : {}", reference.compareAndSet(prev,"C"));
    }

    private static void other() {

        new Thread(() -> {
            log.debug("chang A -> B : {}",reference.compareAndSet(reference.get(), "B"));
        },"t1").start();

        Sleeper.sleep(0.5);

        new Thread(() -> {
            log.debug("chang B -> A : {}",reference.compareAndSet(reference.get(), "A"));
        },"t2").start();
    }
}
